package flinkSql.window.over;

import bean.SensorReading;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.junit.Test;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

//TODO 事件时间滚动窗口
public class Flink_EventTime_OverWindow {

    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map((MapFunction<String, SensorReading>) value -> {
                    String[] split = value.split(",");
                    return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                });

        WatermarkStrategy<SensorReading> watermarkStrategy = WatermarkStrategy.<SensorReading>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                .withTimestampAssigner((SerializableTimestampAssigner<SensorReading>) (element, recordTimestamp) -> element.getTs());

        SingleOutputStreamOperator<SensorReading> input2 = input.assignTimestampsAndWatermarks(watermarkStrategy);

        tableEnvironment.createTemporaryView("sensor",input2,$("id"),$("ts"),$("temp"),$("rt").rowtime());

        Table select = tableEnvironment.sqlQuery("select id,ts,sum(temp) over(partition by id order by rt) ct from sensor");

//        Table select = tableEnvironment.fromDataStream(input2, $("id"), $("ts"), $("temp"),$("rt").rowtime())
//                .window(Over.partitionBy("id").orderBy($("rt")).as("cs"))
//                .select($("id"), $("temp").sum());
//                .select("id,temp.sum over cs");

        select.printSchema();


        tableEnvironment.toRetractStream(select,Row.class).print("sql");

        env.execute();
    }
}
